# main.py - 终极修复版
import os
import sys
import traceback

def setup_environment():
    """设置项目环境"""
    print("=" * 60)
    print("       数据生成与可视化项目 - 终极修复版")
    print("=" * 60)
    
    # 确保在项目根目录
    if not os.path.exists('src'):
        print("❌ 不在项目根目录，尝试自动切换...")
        possible_paths = [
            '.',
            'data-visualization-project',
            '../data-visualization-project'
        ]
        for path in possible_paths:
            if os.path.exists(os.path.join(path, 'src')):
                os.chdir(path)
                print(f"✅ 切换到: {os.getcwd()}")
                break
    
    # 添加src到Python路径
    src_path = os.path.join(os.getcwd(), 'src')
    if src_path not in sys.path:
        sys.path.insert(0, src_path)  # 插入到开头
        print(f"✅ 添加Python路径: {src_path}")
    
    print(f"当前目录: {os.getcwd()}")
    print(f"Python路径: {[p for p in sys.path if 'src' in p]}")
    
    return True

def run_data_generation_safe():
    """安全运行数据生成"""
    print("\n" + "="*50)
    print("   步骤1: 生成模拟数据")
    print("="*50)
    
    try:
        # 检查数据是否已存在
        if os.path.exists('data/raw/sales_data.csv'):
            print("✅ 数据文件已存在，跳过生成")
            return True
        
        # 方法1：尝试导入并运行
        try:
            from data_generation import main as generate_data
            sales_df, employee_df = generate_data()
            print("✅ 数据生成成功（方法1）")
            return True
        except Exception as e:
            print(f"方法1失败: {e}")
        
        # 方法2：直接执行文件
        try:
            print("尝试方法2：直接执行文件...")
            with open('src/data_generation.py', 'r', encoding='utf-8') as f:
                code = f.read()
            exec(code, globals())
            print("✅ 数据生成成功（方法2）")
            return True
        except Exception as e:
            print(f"方法2失败: {e}")
        
        # 方法3：使用importlib
        try:
            print("尝试方法3：使用importlib...")
            import importlib.util
            spec = importlib.util.spec_from_file_location("data_generation", "src/data_generation.py")
            data_module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(data_module)
            data_module.main()
            print("✅ 数据生成成功（方法3）")
            return True
        except Exception as e:
            print(f"方法3失败: {e}")
        
        return False
        
    except Exception as e:
        print(f"❌ 所有数据生成方法都失败: {e}")
        traceback.print_exc()
        return False

def run_visualization_safe():
    """安全运行可视化"""
    print("\n" + "="*50)
    print("   步骤2: 生成可视化图表")
    print("="*50)
    
    try:
        # 方法1：尝试导入main函数
        try:
            from visualization import main as generate_visuals
            generate_visuals()
            print("✅ 可视化成功（方法1）")
            return True
        except Exception as e:
            print(f"方法1失败: {e}")
        
        # 方法2：直接使用类
        try:
            print("尝试方法2：直接使用DataVisualizer类...")
            from visualization import DataVisualizer
            visualizer = DataVisualizer()
            visualizer.create_all_charts()
            print("✅ 可视化成功（方法2）")
            return True
        except Exception as e:
            print(f"方法2失败: {e}")
        
        # 方法3：直接执行文件
        try:
            print("尝试方法3：直接执行文件...")
            with open('src/visualization.py', 'r', encoding='utf-8') as f:
                code = f.read()
            exec(code, globals())
            print("✅ 可视化成功（方法3）")
            return True
        except Exception as e:
            print(f"方法3失败: {e}")
        
        return False
        
    except Exception as e:
        print(f"❌ 所有可视化方法都失败: {e}")
        traceback.print_exc()
        return False

def check_results():
    """检查最终结果"""
    print("\n" + "="*60)
    print("           📋 项目结果检查")
    print("="*60)
    
    # 检查数据文件
    print("\n📊 数据文件:")
    data_files = [
        ('data/raw/sales_data.csv', '销售数据'),
        ('data/raw/user_behavior.csv', '员工数据'),
        ('data/processed/business_data.db', 'SQLite数据库')
    ]
    
    data_success = True
    for file_path, description in data_files:
        if os.path.exists(file_path):
            if file_path.endswith('.csv'):
                try:
                    import pandas as pd
                    df = pd.read_csv(file_path)
                    print(f"  ✅ {description}: {len(df)} 行")
                except:
                    print(f"  ✅ {description}: 文件存在")
            else:
                print(f"  ✅ {description}: 文件存在")
        else:
            print(f"  ❌ {description}: 文件缺失")
            data_success = False
    
    # 检查图表文件
    print("\n📈 可视化图表:")
    chart_files = [
        ('outputs/charts/region_sales_distribution.png', '区域销量分布'),
        ('outputs/charts/age_distribution.png', '年龄段分布'),
        ('outputs/charts/employee_dashboard.png', '员工结构仪表板')
    ]
    
    chart_success = True
    for file_path, description in chart_files:
        if os.path.exists(file_path):
            file_size = os.path.getsize(file_path) / 1024
            print(f"  ✅ {description}: {file_size:.1f} KB")
        else:
            print(f"  ❌ {description}: 文件缺失")
            chart_success = False
    
    return data_success, chart_success

def main():
    """主函数"""
    # 设置环境
    setup_environment()
    
    # 生成数据
    data_success = run_data_generation_safe()
    
    # 生成可视化
    vis_success = False
    if data_success:
        vis_success = run_visualization_safe()
    
    # 检查结果
    data_check, chart_check = check_results()
    
    # 最终总结
    print("\n" + "="*60)
    if data_check and chart_check:
        print("           🎉 项目完全成功！")
        print("="*60)
        print("\n✅ 所有任务完成:")
        print("  • 生成2700条模拟业务数据")
        print("  • 创建3种专业数据可视化图表")
        print("  • 数据文件完整保存")
        print("  • 图表文件成功生成")
    elif data_check and not chart_check:
        print("           ⚠️ 项目部分成功")
        print("="*60)
        print("\n✅ 数据生成成功")
        print("❌ 图表生成失败")
        print("\n💡 建议: 可以单独运行 src/visualization.py")
    else:
        print("           ❌ 项目失败")
        print("="*60)
        print("\n请检查错误信息并重新运行")

if __name__ == "__main__":
    main()